//
//  ViewController.m
//  CollectionView
//
//  Created by Gnnt on 16/3/30.
//  Copyright © 2016年 Gnnt. All rights reserved.
//

#import "ClassificationViewController.h"
#import "Header.h"
#import "ClassIficationCell.h"
#import "ClassCollectionCell.h"

@interface ClassificationViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    NSMutableArray *category_arr;
    UICollectionView *_collectionView;
    UITableView *_tableView;
    BOOL _isRelate;
}

@end

@implementation ClassificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"商品分类"];
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, nil];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = BgColor;
    category_arr = [NSMutableArray arrayWithObjects:@"推荐",@"手机",@"数码",@"母婴",@"食品",@"美妆",@"女装",@"男装",@"百货",@"鞋包",@"洗护",nil];
    [self TableView];
    [self CollectionView];

}
-(UITableView *)TableView{
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH/4,HEIGHT) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor mainBackgroundColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.rowHeight = 45;
        _tableView.scrollEnabled = NO;//不能滑动
        [_tableView registerClass:[ClassIficationCell class] forCellReuseIdentifier:NSStringFromClass([ClassIficationCell class])];
        
        NSIndexPath *firstPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [_tableView selectRowAtIndexPath:firstPath animated:NO scrollPosition:UITableViewScrollPositionTop];//默认选中一行
        
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
-(UICollectionView *)CollectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(WIDTH/4, 0, WIDTH*3/4, HEIGHT - 64) collectionViewLayout:layout];//初始化，并设置布局方式
        _collectionView.backgroundColor = [UIColor whiteColor];
        
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];//注册UICollectionViewCell，这是固定格式，也是必须要实现的
        
        [_collectionView registerNib:[UINib nibWithNibName:@"ClassCollectionCell" bundle:nil] forCellWithReuseIdentifier:NSStringFromClass(ClassCollectionCell.class)];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];//注册头/尾视图
//        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footView"];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    //设置组数，不写该方法默认是一组
    return category_arr.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 13;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        
    if(indexPath.item == 0)
    {
        static NSString *identifier = @"cell";//注意，此处的identifier要与注册cell时使用的标识保持一致
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
        cell.backgroundColor = [UIColor orangeColor];
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = [UIColor whiteColor].CGColor;
     
        UILabel *titleTextLable = [[UILabel alloc]initWithFrame:cell.frame];
        titleTextLable.textColor = [UIColor blackColor];
        
        if ([@"推荐" isEqualToString:category_arr[indexPath.section]]==YES) {
            titleTextLable.text =@"热门分类" ;
        }else{
            titleTextLable.text = category_arr[indexPath.section];
        }
        
        titleTextLable.backgroundColor = [UIColor whiteColor];
        cell.backgroundView = titleTextLable;
        cell.userInteractionEnabled = NO;
        return cell;
    }else
    {
        ClassCollectionCell *cell2 = [collectionView dequeueReusableCellWithReuseIdentifier:@"ClassCollectionCell" forIndexPath:indexPath];
        if(!cell2){
            cell2 = [[NSBundle mainBundle]loadNibNamed:@"ClassCollectionCell" owner:nil options:nil].firstObject;
        }
        cell2.backgroundColor = [UIColor whiteColor];
        cell2.layer.borderWidth = 1;
        cell2.layer.borderColor = [UIColor orangeColor].CGColor;
        cell2.userInteractionEnabled = YES;
        return cell2;
    }
}

//如果用头视图的方法进行相关联会出现，透视图的分类标题不能显示在可视范围
//设置头视图的尺寸，如果想要使用头视图，则必须实现该方法

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
   // return CGSizeMake(WIDTH*3/4, 30);
     return CGSizeMake(WIDTH*3/4,0.5);//在此如果将头视图的尺寸设置为（0，0）则左侧的tableView的分类cell不会根据collectionView的滑动而滑到相应的分类的cell。

}


-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    //根据类型以及标识获取注册过的头视图,
    
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
    headerView.backgroundColor = [UIColor whiteColor];
    
    
    for (UIView *view in headerView.subviews) {
        [view removeFromSuperview];
    }
   /*
    UILabel *label = [[UILabel alloc] initWithFrame:headerView.bounds];

    label.text = category_arr[indexPath.section];
    [headerView addSubview:label];
    label.textColor = [UIColor whiteColor];
    */
    
    return headerView;
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //设置item尺寸
    if(indexPath.item == 0)
    {
        return CGSizeMake(self.view.frame.size.width - WIDTH/4, 45);
    }
    
    return CGSizeMake(self.view.frame.size.width/4.0, self.view.frame.size.width/4.0);
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    //设置组距离上向左右的间距
    return UIEdgeInsetsMake(0,0,0,0);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    //两个item的列间距
    return 0;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    //如果一组中有多行item，设置行间距
    return 0;
}


#pragma mark- tableView delegate
// 行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return category_arr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ClassIficationCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClassIficationCell class])];
    if (cell == nil){
        cell = [[ClassIficationCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:NSStringFromClass([ClassIficationCell class])];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell addline];
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.textLabel.text = category_arr[indexPath.row];
    
  

    return cell;
}



// tableview cell 选中
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (tableView == _tableView) {
        _isRelate = NO;
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//        cell.textLabel.textColor = RGB(51, 152, 218);
        
        [self.TableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
        //将CollectionView的滑动范围调整到tableView相对应的cell的内容
//        [self.TableView reloadData]
        [self.CollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.row] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
        
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ZTLog(@"%zi组，%zi行",indexPath.section,indexPath.item);
    [self showMessage:@"准备跳转小类别" yOffset:1];
}
//将显示视图
-(void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{
    if (_isRelate) {
        
        NSInteger topcellsection = [[[collectionView indexPathsForVisibleItems]firstObject]section];
        if (collectionView == _collectionView) {
            [self.TableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:topcellsection inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
            
        }
    }
}
//将结束显示视图
-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{
    if (_isRelate) {
        NSInteger itemsection = [[[collectionView indexPathsForVisibleItems]firstObject]section];
        if (collectionView == _collectionView) {
            
            //当collectionView滑动时，tableView的cell自动选中相应的分类
            [self.TableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:itemsection inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }

    }
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    _isRelate = YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
